<template>
    <div class="h-full w-full">
      <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
        <template #left-content>
          <div class="flex justify-between flex-col h-full">
            <a-input-search
              v-model:value="searchValue"
              style="margin-bottom: 8px"
              placeholder="请输入"
            />
            <Tree
              v-model:expandedKeys="state.expandedKeys"
              auto-expand-parent
              :tree-data="state.deptTree"
              @select="onTreeSelect"
            >
            </Tree>
          </div>
        </template>
        <template #right-content>
          <DynamicTable
            header-title="操作配置管理"
            show-index
            :data-request="loadTableData"
            :columns="columns"
          >
            <template v-if="isCheckRows" #title>
              <Alert class="w-full" type="info" show-icon>
                <template #message>
                  已选 {{ isCheckRows }} 项
                  <a-button type="link" @click="rowSelection.selectedRowKeys = []">取消选择</a-button>
                </template>
              </Alert>
            </template>
            <template #toolbar>
              <a-button type="primary" @click="openUserModal({})"> <PlusOutlined /> 新增 </a-button>
            </template>
          </DynamicTable>
        </template>
      </SplitPanel>
    </div>
  </template>
  
  <script setup lang="tsx">
    import { ref, reactive, computed, onMounted, h, watch } from 'vue';
    import {
      PlusOutlined,
      EditOutlined,
      DeleteOutlined,
      FileSyncOutlined,
    } from '@ant-design/icons-vue';
    import { Tree, Modal, Alert } from 'ant-design-vue';
    import { userSchemas } from './formSchemas';
    import { baseColumns, type TableListItem, type TableColumnItem } from './columns';
    import type { LoadDataParams } from '@/components/core/dynamic-table';
    import type { TreeDataItem } from '@/core/permission/utils';
    import { SplitPanel } from '@/components/basic/split-panel';
    import { useTable } from '@/components/core/dynamic-table';
    import {
        getOperActionList
    } from '@/api/system/operAction/index';
    import { useFormModal } from '@/hooks/useModal/index';
    import { formatDept2Tree, findChildById, flatTree } from '@/core/permission/utils';
    import { getDepartmentEntityList } from '@/api/organization/depts/depts';
  
    defineOptions({
      name: 'operAction',
    });
  
    interface State {
      PARENT_ID: number[];
      NODE_ACTION_TEMP_NO: number[];
      originData: any;
      deptTree: TreeDataItem[];
    }
  
    const [DynamicTable, dynamicTableInstance] = useTable({ formProps: { autoSubmitOnEnter: true } });
    const [showModal] = useFormModal();
  
    const searchValue = ref('');
  
    const searchTree = (tree, keyword, includeChildren = false) => {
      const newTree: any = [];
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.title.includes(keyword)) {
          if (!state.PARENT_ID.includes(node.key) && node.children && node.children.length) {
            state.PARENT_ID.push(node.key);
          }
          newTree.push({
            ...node,
            children: includeChildren ? searchTree(node.children || [], '', true) : [],
          });
        } else if (node.children) {
          const result = searchTree(node.children, keyword, true);
          if (result.length > 0) {
            state.PARENT_ID.push(node.key);
            newTree.push({ ...node, children: result });
          }
        }
      }
      return newTree;
    };
  
    watch(
      () => searchValue.value,
      (newVal) => {
        state.deptTree = searchTree(state.originData, newVal, true);
      },
    );
  
    const deptListLoading = ref(false);
  
    const state = reactive<State>({
      PARENT_ID: [],
      NODE_ACTION_TEMP_NO: [],
      deptTree: [],
      originData: [],
    });
  
    const orgData = reactive({
      positionList: [],
      rolesList: [],
    });
  
    const rowSelection = ref({
      selectedRowKeys: [] as number[],
      onChange: (selectedRowKeys: number[], selectedRows: TableListItem[]) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        rowSelection.value.selectedRowKeys = selectedRowKeys;
      },
    });
  
    // 是否勾选了表格行
    const isCheckRows = computed(() => rowSelection.value.selectedRowKeys.length);
  
    /**
     * @description 打开用户弹窗
     */
    const openUserModal = async (record: Partial<TableListItem> = {}) => {
      const [formRef] = await showModal({
        modalProps: {
          title: `${record.ACTION_NO ? '编辑' : '新增'}操作`,
          width: 700,
          bodyStyle: { maxHeight: '500px', overflowY: 'auto' },
          onFinish: async (values) => {
            values.ACTION_NO = record.ACTION_NO;
            await (record.ACTION_NO ? updateUser : createUser)(values);
            dynamicTableInstance?.reload();
          },
        },
        formProps: {
          labelWidth: 100,
          schemas: userSchemas(),
          autoSubmitOnEnter: true,
        },
      });
      formRef?.updateSchema([
        {
          field: 'ACTION_NO',
          componentProps: {
            treeDefaultExpandedKeys: findChildById(record?.ACTION_NO, state.originData)?.keyPath || [],
            treeData: state.originData,
          },
        },
      ]);
  
      formRef?.setFieldsValue(record);
      // if (record?.USER_ID) {
      //   const res = await getUserInfo({ username: record.USER_ACCOUNT });
      //   const fileds = {
      //     ...res.result.user,
      //     //positions: res.result.positions.map((item) => item.id),
      //     //roles: res.result.roles.map((item) => item.id),
      //   };
      //   formRef?.setFieldsValue(fileds);
      // }
    };
    /**
     * 获取模版列表
     */
    const fetchDeptList = async () => {
      deptListLoading.value = true;
      const res = await getDepartmentEntityList().finally(() => (deptListLoading.value = false));
      console.log(res);
      if (res && res.result) {
        const dept = flatTree(res.result);
        state.deptTree = formatDept2Tree(dept, '0');
        console.log(state.deptTree,"11111")
        state.originData = state.deptTree.map((item) => item);
        state.PARENT_ID = [...state.PARENT_ID, ...state.deptTree.map((n: any) => Number(n.ID))];
      }
    };
    /**
     * 点击模版
     */
    const onTreeSelect = (selectedKeys: number[]) => {
      state.NODE_ACTION_TEMP_NO = selectedKeys;
      dynamicTableInstance?.reload?.();
    };
  
    const loadTableData = async (params: LoadDataParams) => {
      const data = await getOperActionList({
        ...params,
        pagesize: params.limit,
        departid: state.NODE_ACTION_TEMP_NO.length ? state.NODE_ACTION_TEMP_NO[0] : '',
      });
      rowSelection.value.selectedRowKeys = [];
      return {
        list: data?.result || [],
        pagination: {
          total: data.total,
          size: params.limit,
          page: params.pageNum,
        },
      } as API.TableListResult;
    };
  
    const columns: TableColumnItem[] = [
      ...baseColumns,
      {
        title: '操作',
        width: 250,
        dataIndex: 'ACTION',
        align: 'center',
        actions: ({ record }) => [
          {
            label: '编辑',
            icon: h(EditOutlined),
            onClick: () => openUserModal(record),
          },
          {
            label: '删除',
            danger: true,
            icon: h(DeleteOutlined),
            popConfirm: {
              title: '你确定要删除吗？',
              onConfirm: () => delRowConfirm(record.ACTION_NO),
            },
          },
        ],
      },
    ];
      /**
   * @description 表格删除行
   */
    const delRowConfirm = async (ACTION_NO: number) => {
        await deleteUsers({ ACTION_NO: ACTION_NO }).finally(dynamicTableInstance?.reload);
    };
    onMounted(() => {
      fetchDeptList();
    });
  </script>
  
  <style lang="less" scoped>
    @import '@/styles/navTheme.less';
    @classBacks: user-page-box;
    .customSetStyle(@classBacks, background-color, 'content-back-user');
  
    :deep(.ant-tree) {
      flex: 1;
    }
  </style>
  